package com.zznode.redsun.commons.sercurity.action;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;

import com.zznode.redsun.commons.utils.AbstractBaseAction;

@Controller
@Namespace("/")
public class LoginAction extends AbstractBaseAction {
	private static final long serialVersionUID = 1L;
	private static final Logger logger = LoggerFactory.getLogger(LoginAction.class);

	@Action(value = "submit", results = { @Result(name = INPUT, location = "login.jsp"),
			@Result(name = SUCCESS, type = "redirect", location = "/console/index.do") })
	public String submit() {
		String username = this.getParameter("username");
		String password = this.getParameter("password");
		logger.debug("===>>username : " + username + "\tpassword : " + password);
		try {
			Subject subject = SecurityUtils.getSubject();
			UsernamePasswordToken accountToken = new UsernamePasswordToken(username, password);
			this.putValueStack("username", username);
			subject.login(accountToken);
			return SUCCESS;
		} catch (UnknownAccountException ex) {
			this.addActionMessage("用户[" + username + "]不存在.");
			logger.warn("用户[" + username + "]不存在:" + ex.getMessage());
			return INPUT;
		} catch (LockedAccountException ex) {
			this.addActionMessage("用户[" + username + "]已锁定，请与管理员联系.");
			logger.warn("用户[" + username + "]已锁定，请与管理员联系:" + ex.getMessage());
			return INPUT;
		} catch (IncorrectCredentialsException ex) {
			this.addActionMessage("帐号或密码错误.");
			logger.warn("帐号或密码错误:" + ex.getMessage());
			return INPUT;
		} catch (AuthenticationException ex) {
			this.addActionMessage("帐号或密码错误.");
			logger.warn("帐号或密码错误:" + ex.getMessage());
			return INPUT;
		} catch (Exception ex) {
			this.addActionMessage("系统错误：" + ex.getMessage());
			logger.warn("系统错误：" + ex.getMessage(), ex);
			return INPUT;
		}
	}

	@Action(value = "logout", results = { @Result(name = SUCCESS, location = "login.jsp") })
	public String logout() {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return SUCCESS;
	}

}
